package com.levy.contronller.javase.nio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * Created by levy on 2018/7/30.
 */
public class NioTest {

    public static void main(String[] args) throws IOException {

        File file = new File("G:\\catalina.out");
        //以只读模式来创建通道
        FileChannel inChannel = new RandomAccessFile(file,"r").getChannel();
        //创建字节缓冲区
        ByteBuffer bytebuf = ByteBuffer.allocate(1024);
        //默认字符集创建解码器
        CharsetDecoder decoder = Charset.defaultCharset().newDecoder();

        while((inChannel.read(bytebuf)) != -1) {//读取通道数据到缓冲区中,非-1就代表有数据
            //确定缓冲区数据的起点和终点
            bytebuf.flip();
            //对bytebuf进行解码，避免乱码
            CharBuffer decode = decoder.decode(bytebuf);
            System.out.println(decode.toString());
            //清空缓冲区，再次放入数据
            bytebuf.clear();
        }

    }
}
